package leetcode_周赛._2021._202111;

import general_class.ListNode;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/11/14 11:09
 */
public class _5972 {
    public static void main(String[] args) {
        // [5,2,6,3,9,1,7,3,8,4]
        ListNode head = new ListNode(5);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(9);
        head.next.next.next.next.next = new ListNode(1);
        head.next.next.next.next.next.next = new ListNode(7);
        head.next.next.next.next.next.next.next = new ListNode(3);
        head.next.next.next.next.next.next.next.next = new ListNode(8);
        head.next.next.next.next.next.next.next.next.next = new ListNode(4);
        new _5972().reverseEvenLengthGroups(head);
    }

    public ListNode reverseEvenLengthGroups(ListNode head) {
        int cnt = 1;
        ListNode cur = head;
        ListNode pre = cur;
        while (cur != null) {
            ListNode tmp = cur;
            int len = 1;
            for (int i = 0; i < cnt - 1 && tmp.next != null; i++) {
                tmp = tmp.next;
                ++len;
            }
            if (cnt % 2 == 0) pre.next = reverse(cur, len, tmp.next);
            pre = cur;
            cur = tmp.next;
            ++cnt;
        }
        return head;
    }
    ListNode reverse(ListNode head, int len, ListNode nextt) {
        ListNode prev = null;
        ListNode curr = head;
        int lenn = len;
        while (curr != null && len > 0) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
            --len;
        }
        ListNode tmp = prev;
        for (int i = 0; i < lenn && tmp != null && tmp.next != null; i++) tmp = tmp.next;
        tmp.next = nextt;
        return prev;
    }

}
